//
//  MKStoreManager.m
//
//  Created by Mugunth Kumar on 15-Nov-09.
//  Copyright 2009 Mugunth Kumar. All rights reserved.
//  mugunthkumar.com
//

#import "MKStoreManager.h"
#import "Utility.h"

@implementation MKStoreManager

@synthesize purchasableObjects;
@synthesize storeObserver;

// all your features should be managed one and only by StoreManager
//static NSString *subscribeId = @"com.whisperingword.whipser.premiumcontent";

//BOOL subscribed = NO;
//BOOL checked = NO;

static __weak id<MKStoreKitDelegate> _delegate;
static MKStoreManager* _sharedStoreManager; // self

- (void)dealloc {
	[_sharedStoreManager release];
	[storeObserver release];
	[super dealloc];
}

+ (id)delegate {
	
    return _delegate;
}

+ (void)setDelegate:(id)newDelegate {
	
    _delegate = newDelegate;	
}
/*
- (BOOL) isSubscribed {
	if (!checked && !subscribed) {
		checked = YES;
		NSString *uniqueID = [[UIDevice currentDevice] uniqueIdentifier];
		NSString * url = [NSString stringWithFormat:checkiPhoneID, uniqueID];
		NSString* ret = [DataSource sendWithEscapeURL:url];
		subscribed = [ret boolValue];
	}
	return subscribed;
}
*/
+ (MKStoreManager*)sharedManager
{
	@synchronized(self) {
		
        if (_sharedStoreManager == nil) {
			
            [[self alloc] init]; // assignment not done here
			_sharedStoreManager.purchasableObjects = [[NSMutableArray alloc] init];			
			[_sharedStoreManager requestProductData];
			/*
			NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];	
			BOOL purchasedAndSubscribed = [userDefaults boolForKey:subscribeId];
			if (!purchasedAndSubscribed) {
				[_sharedStoreManager registSubscribed];
			}
			*/
			_sharedStoreManager.storeObserver = [[MKStoreObserver alloc] init];
			[[SKPaymentQueue defaultQueue] addTransactionObserver:_sharedStoreManager.storeObserver];
        }
    }
    return _sharedStoreManager;
}


#pragma mark Singleton Methods

+ (id)allocWithZone:(NSZone *)zone

{	
    @synchronized(self) {
		
        if (_sharedStoreManager == nil) {
			
            _sharedStoreManager = [super allocWithZone:zone];			
            return _sharedStoreManager;  // assignment and return on first allocation
        }
    }
	
    return nil; //on subsequent allocation attempts return nil	
}


- (id)copyWithZone:(NSZone *)zone
{
    return self;	
}

- (id)retain
{	
    return self;	
}

- (unsigned)retainCount
{
    return UINT_MAX;  //denotes an object that cannot be released
}

- (void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;	
}


- (void) requestProductData
{
	
	NSArray* productArray = [[NSArray alloc] initWithObjects:@"com.jusoft.vnexpress.removeads",nil];
	/*NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];	
	//[userDefaults setBool:YES forKey: productIdentifier];
	for (NSInteger i=0; i<[productArray count]; i++) {
		//[productDict setObject:@"NO" forKey:[productArray objectAtIndex:i]];
		[userDefaults setBool:YES forKey: [productArray objectAtIndex:i]];
	}*/
	
	SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers: 
								 [NSSet setWithArray:productArray]];
	request.delegate = self;
	[request start];
}


- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
	[purchasableObjects addObjectsFromArray:response.products];
	// populate UI
	for(int i=0;i<[purchasableObjects count];i++)
	{
		
		SKProduct *product = [purchasableObjects objectAtIndex:i];
		NSLog(@"Feature: %@, Cost: %f, ID: %@",[product localizedTitle],
			  [[product price] doubleValue], [product productIdentifier]);
	}
	
	[request autorelease];
}

- (void) buyEbookWithProductId: (NSString*) productId
{
	return [self buyFeature:productId];
}
- (void) buyFeature:(NSString*) featureId
{
	if ([SKPaymentQueue canMakePayments])
	{
		SKPayment *payment = [SKPayment paymentWithProductIdentifier:featureId];
		[[SKPaymentQueue defaultQueue] addPayment:payment];
//		if([featureId isEqualToString:subscribeId])[self registSubscribed];
		//return YES;
	}
	else	
	{
//		if([featureId isEqualToString:subscribeId]) subscribed = NO;

		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"You are not authorized to purchase from AppStore"
													   delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
		[alert show];
		[alert release];
		//return NO;
	}
}

/*							 
- (BOOL) buySubscribe
{
	return [self buyFeature:subscribeId];
}
*/
- (void) restorePurchase
{
	[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
	//if([featureId isEqualToString:subscribeId]) subscribed = NO;
	NSString *messageToBeShown = [NSString stringWithFormat:@"Reason: %@, You can try: %@", [transaction.error localizedFailureReason], [transaction.error localizedRecoverySuggestion]];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unable to complete your purchase" message:messageToBeShown
												   delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
	[alert show];
	[alert release];
}

-(void) provideContent: (NSString*) productIdentifier shouldSerialize: (BOOL) serialize
{
	if(serialize)
	{
		if([_delegate respondsToSelector:@selector(productPurchased:)])
			[_delegate productPurchased:productIdentifier];
		NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];	
		[userDefaults setBool:YES forKey: productIdentifier];
		[userDefaults synchronize];
	}
}
- (void)updateProVersion
{
	return [self buyFeature:@"com.jusoft.vnexpress.removeads"];
}
/*
-(void)registSubscribed {
	subscribed = YES;
	NSString *uniqueID = [[UIDevice currentDevice] uniqueIdentifier];
	NSString *url = [NSString stringWithFormat:registPhoneID, uniqueID];
	NSString *result = [DataSource sendWithEscapeURL:url];
	
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	if ([result isEqualToString:@"YES"]) {
		[userDefaults setBool:YES forKey:subscribeId];
	} else {
		[userDefaults setBool:NO forKey:subscribeId];
	}
	[userDefaults synchronize];
}
*/
- (void) restoreCompleted
{
	[Utility showAlert:@"Restoration completed!"];
}

- (void) restoreFailed
{
	[Utility showAlert:@"Restoration Failed! You can enable restore funtion from Settings page!"];
}

- (void) productPurchased: (NSString*) productId
{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];	
	[userDefaults setBool:YES forKey: productId];
	[userDefaults synchronize];
    
}

- (BOOL) isPurchased: (NSString*) productId
{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];	
	return [userDefaults boolForKey:productId];
}
@end
